﻿using System.IO;
using System.Xml;


namespace CSP.CRM.Deployer
{
  public class ISVExtensionsDeployer
  {
    private TextWriter log;
    private string cspPrefix;
    private string organizationName;
    

    public ISVExtensionsDeployer(string cspPrefix, string organizationName, TextWriter log)
    {
      this.log = log;
      this.cspPrefix = cspPrefix;
      this.organizationName = organizationName;
    }


    public void Run()
    {
      string cspIsvPath = CRMRegistry.CrmWebSitePath + @"\ISV\CSP";
      string crmBinPath = CRMRegistry.CrmWebSitePath + @"\bin";
      log.WriteLine("Creating dir " + cspIsvPath);
      Directory.CreateDirectory(cspIsvPath);
      string sourceDir = Directory.GetCurrentDirectory() + @"\files\";
      CopyFiles(sourceDir, cspIsvPath, new string[] { "Web.config" });
      CopyWildcard(sourceDir, cspIsvPath, "*.aspx");
      CopyWildcard(sourceDir, cspIsvPath, "*.gif");
      CopyFiles(sourceDir, crmBinPath, new string[] { @"CSP.CRM.ISVExtensions.dll" });

      //string isvWebConfigPath = cspIsvPath + @"\Web.config";
      //TrimWebConfig(isvWebConfigPath);
    }

    private void CopyFiles(string sourceDir, string destinationDir, string[] fileNames)
    {
      foreach (string fileName in fileNames)
      {
        string sourceFile = sourceDir + @"\" + fileName;
        string destinationFile = destinationDir + @"\" + fileName;
        log.WriteLine("Copying " + Path.GetFileName(fileName));
        File.Copy(sourceFile, destinationFile, true);        
      }
    }

    private void CopyWildcard(string sourceDir, string destinationDir, string wildCard)
    {
      string[] fileNames = Directory.GetFiles(sourceDir, wildCard);
      foreach (string fileName in fileNames)
      {
        string fileNameWithoutPath = Path.GetFileName(fileName);
        string sourceFile = sourceDir + @"\" + fileNameWithoutPath;
        string destinationFile = destinationDir + @"\" + fileNameWithoutPath;
        log.WriteLine("Copying " + fileNameWithoutPath);
        File.Copy(sourceFile, destinationFile, true);
      }
    }

    private void TrimWebConfig(string isvWebConfigPath)
    {
      log.WriteLine("Trimming " + isvWebConfigPath);
      XmlDocument configDoc = new XmlDocument();
      configDoc.Load(isvWebConfigPath);

      string organizationNameXPath = @"/configuration/appSettings/add[@key='OrganizationName']";
      XmlElement orgNameNode = configDoc.SelectSingleNode(organizationNameXPath) as XmlElement;
      orgNameNode.SetAttribute("value", organizationName);

      configDoc.Save(isvWebConfigPath);
    }


  }
}
